<!-- 字典数据 -->
<script setup lang="ts">
import { getDictPage, addDict, deleteDict } from "@/api/dict";
import { DictPageVO, DictForm, DictQuery } from "@/api/dict/types";
import { filterOrder } from "@/utils/commonHooks";

defineOptions({
  name: "DictData",
  inheritAttrs: false,
});

const props = defineProps({
  typeCode: {
    type: String,
    default: () => {
      return "";
    },
  },
  typeName: {
    type: String,
    default: () => {
      return "";
    },
  },
  id: {
    type: String,
    default: () => {
      return "";
    },
  },
});

watch(
  () => props.typeCode,
  (newVal: string) => {
    queryParams.data.dictionaryCode = newVal;
    formData.dictionaryCode = newVal;
    resetQuery();
  }
);

const queryFormRef = ref(ElForm);
const dataFormRef = ref(ElForm);

const loading = ref(false);
const ids = ref<number[]>([]);
const queryTotal = ref(0);

const queryParams = reactive<DictQuery>({
  current: 1,
  size: 10,
  data: {
    dictionaryCode: props.typeCode,
    itemLabel: "",
  },
  sort: {
    column: "dictionary_code",
    orderBy: "asc",
  },
});

const dictList = ref<DictPageVO[]>();

const dialog = reactive<DialogOption>({
  visible: false,
});

const formData = reactive<DictForm>({
  enabled: 1,
  dictionaryCode: props.typeCode,
  sort: 1,
  itemValue: "",
  itemLabel: "",
  remarks: "",
});

const rules = reactive({
  itemLabel: [
    { required: true, message: "请输入字典名称", trigger: "blur" },
    { max: 45, message: "字典名称不能超过45个字符", trigger: "blur" },
  ],
  itemValue: [
    { required: true, message: "请输入字典值", trigger: "blur" },
    { max: 45, message: "字典值不能超过45个字符", trigger: "blur" },
  ],
});

/**
 * 查询
 */
function handleQuery() {
  if (queryParams.data.dictionaryCode) {
    loading.value = true;
    getDictPage(queryParams)
      .then((res: any) => {
        const { total, data } = res;
        dictList.value = data;
        queryTotal.value = total;
      })
      .finally(() => (loading.value = false));
  }
}

/**
 * 重置查询
 */
function resetQuery() {
  queryFormRef.value.resetFields();
  queryParams.current = 1;
  handleQuery();
}

/**
 * 排序
 *
 * @param column
 */
function onTableSortChanged(column: any) {
  const { prop, order } = column;
  queryParams.sort = {
    column: prop,
    orderBy: filterOrder(order),
  };

  handleQuery();
}

/**
 * 行checkbox change事件
 *
 * @param selection
 */
function handleSelectionChange(selection: any) {
  ids.value = selection.map((item: any) => item.id);
}

/**
 * 打开字典表单弹窗
 *
 * @param id 字典ID
 */
function openDialog(data?: any) {
  dialog.visible = true;
  if (data?.id) {
    dialog.title = "修改字典";
    const { enabled, dictionaryCode, sort, itemValue, itemLabel, remarks, id } =
      data;
    Object.assign(formData, {
      enabled,
      dictionaryCode,
      sort,
      itemValue: itemValue,
      itemLabel,
      remarks,
      id,
    });
  } else {
    delete formData.id;
    dialog.title = "新增字典";
  }
}

/**
 * 字典表单提交
 */
function handleSubmit() {
  dataFormRef.value.validate((isValid: boolean) => {
    if (isValid) {
      loading.value = true;
      addDict(formData)
        .then(() => {
          ElMessage.success("新增成功");
          closeDialog();
          resetQuery();
        })
        .finally(() => (loading.value = false));
    }
  });
}

/**
 * 关闭弹窗
 */
function closeDialog() {
  dialog.visible = false;
  resetForm();
}

/**
 * 重置表单
 */
function resetForm() {
  dataFormRef.value.resetFields();
  dataFormRef.value.clearValidate();

  formData.id = undefined;
  formData.enabled = 1;
  formData.sort = 1;
  formData.dictionaryCode = props.typeCode;
  formData.itemValue = "";
  formData.itemLabel = "";
  formData.remarks = "";
}

/**
 * 删除字典
 */
const deleteLoading = ref(false);
function handleDelete(dictId?: number) {
  const dictIds = [dictId || ids.value].join(",");
  if (!dictIds) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    const dictIdsArr = dictIds.split(",");
    const data = {
      dictionaryCode: props.typeCode,
      ids: dictIdsArr,
    };
    deleteLoading.value = true;
    deleteDict(data)
      .then(() => {
        ElMessage.success("删除成功");
        handleQuery();
      })
      .finally(() => {
        deleteLoading.value = false;
      });
  });
}

onMounted(() => {
  handleQuery();
});
</script>

<template>
  <div class="app-container">
    <div class="search-container">
      <!-- 搜索表单 -->
      <el-form ref="queryFormRef" :model="queryParams.data" :inline="true">
        <el-form-item label="字典名称" prop="itemLabel">
          <el-input
            v-model="queryParams.data.itemLabel"
            placeholder="请输入字典名称"
            clearable
          />
        </el-form-item>
        <el-form-item label="字典值" prop="itemValue">
          <el-input
            v-model="queryParams.data.itemValue"
            placeholder="请输入字典值"
            clearable
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery"
            ><i-ep-search />搜索</el-button
          >
          <el-button @click="resetQuery"> <i-ep-refresh />重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-card shadow="never" class="table-container">
      <template #header>
        <el-button type="success" @click="openDialog()"
          ><i-ep-plus />新增</el-button
        >
        <el-button
          type="danger"
          :disabled="ids.length === 0"
          :loading="deleteLoading"
          @click="handleDelete()"
          ><i-ep-delete />删除</el-button
        >
      </template>

      <!-- 数据表格 -->
      <el-table
        v-loading="loading"
        :data="dictList"
        border
        @selection-change="handleSelectionChange"
        @sort-change="onTableSortChanged"
      >
        <el-table-column type="selection" width="50" />
        <el-table-column label="字典名称" prop="itemLabel" />
        <el-table-column label="字典值" prop="itemValue" align="center" />
        <el-table-column
          sortable="custom"
          label="排序"
          prop="sort"
          width="80"
          align="center"
        />

        <el-table-column label="是否启用" align="center" width="100">
          <template #default="scope">
            <el-tag v-if="scope.row.enabled === 1" type="success">启用</el-tag>
            <el-tag v-else type="info">禁用</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          label="备注"
          prop="remarks"
          align="center"
          show-overflow-tooltip
        />
        <el-table-column fixed="right" label="操作" align="center">
          <template #default="scope">
            <el-button type="primary" link @click="openDialog(scope.row)"
              ><i-ep-edit />编辑</el-button
            >
            <el-button
              type="primary"
              link
              @click.stop="handleDelete(scope.row.id)"
              ><i-ep-delete />删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-if="queryTotal > 0"
        v-model:total="queryTotal"
        v-model:page="queryParams.current"
        v-model:limit="queryParams.size"
        @pagination="handleQuery"
      />
    </el-card>

    <!-- 表单弹窗 -->
    <el-dialog
      :close-on-click-modal="false"
      v-model="dialog.visible"
      :title="dialog.title"
      width="600px"
      @close="closeDialog"
    >
      <el-form
        ref="dataFormRef"
        :model="formData"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="字典类别">{{ typeName }}</el-form-item>
        <el-form-item label="字典名称" prop="itemLabel">
          <el-input v-model="formData.itemLabel" placeholder="请输入字典名称" />
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item label="字典项值" prop="itemValue">
              <el-input
                v-model="formData.itemValue"
                placeholder="请输入字典项值"
                maxlength="20"
                show-word-limit
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="排序" prop="sort">
              <el-input-number
                :min="0"
                controls-position="right"
                autocomplete="off"
                v-model="formData.sort"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="是否启用" prop="enabled">
          <el-radio-group v-model="formData.enabled">
            <el-radio :label="1">正常</el-radio>
            <el-radio :label="0">停用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remarks">
          <el-input
            v-model="formData.remarks"
            type="textarea"
            placeholder="请输入备注"
            show-word-limit
            :maxlength="250"
            :autosize="{ minRows: 3, maxRows: 4 }"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
